package site.ruolin.Decrypt;

import site.ruolin.KeyGen.Key.PrivateKey;
import site.ruolin.KeyGen.Key.PublicKey;
import site.ruolin.Util.MathUtil;

import java.math.BigInteger;

/**
 * 解密
 * @author ruolin on 2025/09/11
 */
public class Decrypt {
    private final PrivateKey privateKey;
    private final PublicKey publicKey;

    /**
     * 构造函数
     * @param privateKey 私钥
     * @param publicKey 公钥
     */
    public Decrypt(PrivateKey privateKey, PublicKey publicKey) {
        this.privateKey = privateKey;
        this.publicKey = publicKey;
    }

    /**
     * 解密
     * @param cipherText 密文
     * @return 明文
     */
    public BigInteger decrypt(BigInteger cipherText) {
        // 计算 m = L(c^λ mod n^2) * μ mod n
        BigInteger cLambda = cipherText.modPow(privateKey.getLambda(), publicKey.getNSquare());
        BigInteger L_result = MathUtil.L(cLambda, publicKey.getN());

        return L_result.multiply(privateKey.getMu()).mod(publicKey.getN());
    }
}
